package cn.itsource.pet.service.impl;

import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.pet.domain.PetType;
import cn.itsource.pet.mapper.PetTypeMapper;
import cn.itsource.pet.service.IPetTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 业务实现类：
 */
@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class PetTypeServiceImpl extends BaseServiceImpl<PetType> implements IPetTypeService {

    @Autowired
    private PetTypeMapper petTypeMapper;

    @Override
    public List<PetType> queryTree() {
        List<PetType> allPets = petTypeMapper.findAll();
        HashMap<Long,PetType> allPetMap = new HashMap<>();

        List<PetType> petTree = new ArrayList<>();
        for (PetType pet : allPets){
            allPetMap.put(pet.getId(),pet);
        }

        for (PetType temp :allPets){
            if(temp.getParentId()==null){
                petTree.add(temp);
            }else{
                PetType parent = allPetMap.get(temp.getParentId());
                if(parent!=null){
                    parent.getChildren().add(temp);
                }
            }
        }
        return petTree;
    }
}
